package network_programming.np1_socket_and_serversocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class EchoServerHandler implements Runnable {     // 负责与单个客户通信
    private final Socket socket;
    public EchoServerHandler(Socket socket) {
        this.socket = socket;
    }
    private BufferedReader getReader(Socket socket) throws IOException {
        InputStream socketIS = socket.getInputStream();
        return new BufferedReader(new InputStreamReader(socketIS));
    }
    private PrintWriter getWriter(Socket socket) throws IOException {
        OutputStream socketOS = socket.getOutputStream();
        return new PrintWriter(socketOS, true);
    }
    @Override
    public void run() {
        try {
            System.out.println("New connection accepted " + socket.getInetAddress() +
                    ":" + socket.getPort());
            BufferedReader br = getReader(socket);
            PrintWriter pw = getWriter(socket);
            String msg = null;
            while((msg = br.readLine()) != null) {
                System.out.println("接收到：" + msg);
                pw.println(echo(msg));
                if(msg.equals("bye"))
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket != null) {
                try {
                    socket.close();     // 断开连接
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public String echo(String msg) {
        return "echo: " + msg;
    }
}
